Skip to content

canvas: Reuse parsed SVG paths across drawings - #4213

Draft
lurenjia534 wants to merge 1 commit into
longbridge:mainfrom
lurenjia534:perf/path2d-parsed-path
Draft

lurenjia534 wants to merge 1 commit into
longbridge:mainfrom
lurenjia534:perf/path2d-parsed-path

Conversation

@lurenjia534

@lurenjia534 lurenjia534 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Description

QuickJS's Path2D(svg) kept the SVG source in its recording. Every fill, stroke or clip decoded that source again, including repeated uses of the same path in later drawings.

Parse the SVG once in the constructor and keep an immutable Arc<[PathOp]> in the native recording. A drawing that uses that SVG segment alone receives the same geometry. Copies and addPath snapshots share the segment; composite paths assemble their operations in order, with animated arguments still decoded against the current drawing's slots. This avoids sharing drawing-local animation indices.

The browser recorder's existing [CV_SVG_PATH, string] representation remains supported. There is no global cache, new canvas opcode, or change to the Drawing format consumed by platform renderers.

Public API

nsh-core, nsh_core::js::host::HostInput:

fn canvas_path(&self) -> Option<nsh_core::canvas::Path>

An optional hook for a host input to supply immutable canvas geometry containing only constant coordinates. Its default implementation returns None, so existing host implementations continue to use the string decoder without adding a method.

The hook is needed to pass the QuickJS recorder's parsed geometry through the shared decoder. These runtime-owned recording and decoding steps cannot be changed by an app or an nshm. This adds no JavaScript/TypeScript API.

Performance

Compared with main 59a945f04b1340482962532dec945c33df8fe2d2 on Linux x86_64, Rust 1.100.1. Both CLIs use the workspace's development optimization levels, with debug info and incremental compilation disabled. Three alternating before/after runs; five warmups followed by 20 measured presses per mode per run. The table reports median / nearest-rank p95 of the pooled 60 event js samples, in microseconds.

SVG line segments Event Before After
4 64 strokes of one retained path 204 / 336 108 / 187
128 64 strokes of one retained path 1432 / 1787 125.5 / 228
4 64 paths constructed and stroked once each 283 / 366 283 / 374
128 64 paths constructed and stroked once each 1523.5 / 1992 1509.5 / 2060
4 256 paths constructed and replaced, without drawing 221 / 325 521 / 623
128 256 paths constructed and replaced, without drawing 250.5 / 394 5255.5 / 6027

Every redraw has the same 1 op / 1 mount item / 9 nodes; construction alone submits no drawing. The retained-path event median falls by about 47% for four line segments and 91% for 128. Constructing and drawing once is essentially unchanged. Construction alone is slower because it now includes parsing, even if the path is never drawn.

These measurements cover the JS callback, recording and decoding, not native path construction, painting or frame rate. Composite paths still assemble their geometry, and recording snapshots still allocate small lists.

The counter control (nsh test examples/counter/App.tsx --trace, three alternating runs, 25 presses each, first five discarded) has identical commit sequences, including 56 ops / 50 mount items / 15 nodes initially. Its event medians are 162.5 / 147 microseconds and first-frame ranges 6.75–7.94 / 6.08–10.13 ms; no broader runtime speedup is claimed.

The reproducible workload is examples/bench/CanvasPaths.tsx, with results and methodology in docs/dev/performance.md. Press each of id:reuse, id:fresh and id:construct 25 times, discard each mode's first five samples, and change SEGMENTS to 4 for the small path. Redirect the full trace because it prints all path operations.

How to Test

Completed locally:

  • cargo build -p nsh-cli.
  • cargo test -p nsh-engine --test engine canvas::: 10 passed, including the two new regression tests and existing OffscreenCanvas, hit-test and redraw coverage.
  • cargo test -p nsh-core --lib canvas::tests::: 10 passed, reusing the existing SVG parser and malformed-prefix checks.
  • The same two new tests against main: the sharing test fails on Arc::ptr_eq, while the snapshot/animation test passes. This confirms the test catches the original problem.
  • nsh test --trace before/after for the path benchmark and counter control, as above. An additional headless probe verified empty/invalid SVG paths do not fall back to the current context path, valid SVG hit testing works, and malformed data retains its valid prefix.
  • cargo xtask compat: passed, including the checkout apps and the full coverage-claim checks.
  • cargo clippy -p nsh-core -p nsh-js -p nsh-engine --all-targets: passed.
  • Nightly rustfmt checks on all four changed Rust files, and git diff --check.

Only two regression tests were added. One checks real emitted geometry and sharing across fill/stroke/clip, copies, addPath and redraws; the other protects mutation snapshots, self-add, composite paths and animation-slot rebinding. There are no timing thresholds or duplicate parser tests.

Whole-workspace cargo +nightly fmt --all -- --check reports the same pre-existing formatting differences in 18 unchanged files on both the baseline and this branch; the two diagnostic logs are byte-for-byte identical. The changed Rust files pass. Native GUI/FPS checks and the full multi-platform workspace suite were not run for this recorder/decoder change.

Parse SVG once in the QuickJS Path2D constructor and share immutable
geometry through recording snapshots. Keep composite paths and animated
arguments bound to each drawing, and retain the browser string decoder.

Cover shared geometry and snapshot/animation semantics with two focused
regression tests. The sharing test fails on main and passes here.

Linux x86_64 development builds, 64 strokes per redraw: event medians
fall from 204 to 108 us for 4 segments and 1432 to 125.5 us for 128.
Both versions submit 1 op / 1 mount item / 9 nodes. One-use paths cost
about the same; construction alone now pays for parsing. Add a reusable
benchmark and document the measurements and tradeoff.
@huacnlee

huacnlee commented Dec 3, 2026

Copy link
Copy Markdown
Member

❌ The win on reused paths is real, but eager parsing makes construct-only workloads ~20x slower, and a public trait method is added just for plumbing.

  • crates/nsh-js/src/canvas.rs (path_2d, ~L1242): svg_path(...) now runs eagerly in the Path2D constructor. The PR's own table shows "256 paths constructed and replaced" going 250 -> 5255 µs median at 128 segments. Please parse lazily on first use and cache the Arc, so undrawn paths cost nothing.
  • crates/nsh-core/src/js/host.rs:60: HostInput::canvas_path is a new public trait method only used by the QuickJS recorder. Please make it #[doc(hidden)]/crate-internal, or justify it as public API.
  • crates/nsh-core/src/js/canvas.rs:131-140: fast path only applies when the SVG segment is the whole path; composite paths still copy. Fine, but document it.
  • Measurements cover the JS callback and decoding only, not native paint or frame time; real-app benefit is unproven.

Reviewed head: b395c7b (read-only diff review; not built locally).

🤖 Noop (reviewer) · AI agent acting for @huacnlee

@lurenjia534
lurenjia534 marked this pull request as draft December 3, 2026 13:01

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants